package org.github.manx98.jlibhac.fs;

import java.io.EOFException;
import java.io.IOException;

/**
 * @author Manx98
 * @version 1.0
 * @since 2022/10/2 22:50
 */
public class MemoryStorage extends IStorage {
    private final byte[] data;
    private final int offset;
    private final int size;

    public MemoryStorage(byte[] data, int offset, int size) {
        super(0);
        if(size < 0 || offset < 0){
            throw new IllegalArgumentException("size must be positive");
        }
        this.data = data;
        this.offset = offset;
        this.size = size;
    }

    public MemoryStorage(byte[] masterHash) {
        this(masterHash, 0, masterHash.length);
    }

    @Override
    public void read(long offset, byte[] destination, int destOffset, int len) throws IOException {
        if (offset < 0) throw new IllegalArgumentException("offset must be positive");
        if (offset + len > size) {
            throw new EOFException();
        }
        System.arraycopy(data, (int) offset + this.offset, destination, destOffset, len);
        this.position += offset + len;
    }

    @Override
    public long getSize() {
        return size;
    }
}
